package com.ibpd.henuocms.web.controller.manage;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gwt.user.client.Random;
import com.ibpd.dao.impl.HqlParameter;
import com.ibpd.dao.impl.ServiceProxyFactory;
import com.ibpd.dao.impl.HqlParameter.DataType_Enum;
import com.ibpd.entity.baseEntity.IBaseEntity;
import com.ibpd.henuocms.assist.OrderMap;
import com.ibpd.henuocms.assist.PermissionModelEntity;
import com.ibpd.henuocms.common.IbpdLogger;
import com.ibpd.henuocms.common.RandomUtil;
import com.ibpd.henuocms.common.SysUtil;
import com.ibpd.henuocms.common.TxtUtil;
import com.ibpd.henuocms.common.UnZip;
import com.ibpd.henuocms.common.Zip;
import com.ibpd.henuocms.entity.ContentAttrEntity;
import com.ibpd.henuocms.entity.ContentEntity;
import com.ibpd.henuocms.entity.NodeEntity;
import com.ibpd.henuocms.entity.NodeFormEntity;
import com.ibpd.henuocms.entity.ext.NodeFormExtEntity;
import com.ibpd.henuocms.service.content.ContentServiceImpl;
import com.ibpd.henuocms.service.content.IContentService;
import com.ibpd.henuocms.service.contentAttr.ContentAttrServiceImpl;
import com.ibpd.henuocms.service.contentAttr.IContentAttrService;
import com.ibpd.henuocms.service.node.INodeService;
import com.ibpd.henuocms.service.node.NodeServiceImpl;
import com.ibpd.henuocms.service.nodeAttr.INodeAttrService;
import com.ibpd.henuocms.service.nodeAttr.NodeAttrServiceImpl;
import com.ibpd.henuocms.service.nodeForm.INodeFormService;
import com.ibpd.henuocms.service.nodeForm.NodeFormServiceImpl;

@Controller
public class Content extends BaseController {
	IContentService contentService = null;

	@RequestMapping("Manage/Content/index.do")
	public String index(Model model, String nodeId, HttpServletRequest req)
			throws IOException { 
		String id = nodeId;
		model.addAttribute("nodeId", nodeId);
		if (id.indexOf("_") == -1) {
			model.addAttribute("permissionEnable_contAdd",
					SysUtil.checkPermissionIsEnable(req.getSession(),
							"cont_add", Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_contEdit", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_edit",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_contDel",
					SysUtil.checkPermissionIsEnable(req.getSession(),
							"cont_del", Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_contReload", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_reload",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_contMove", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_move",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_contLink", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_link",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_contCopy", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_copy",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_contLock", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_lock",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_contTop",
					SysUtil.checkPermissionIsEnable(req.getSession(),
							"cont_top", Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_contRecommend", SysUtil
					.checkPermissionIsEnable(req.getSession(),
							"cont_recommend", Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_contExport", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_export",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_contImport", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_import",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_contPublish", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_publish",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_contSearch", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_search",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_NODE));
		} else {
			id = nodeId.split("_")[1];
			model.addAttribute("permissionEnable_contAdd",
					SysUtil.checkPermissionIsEnable(req.getSession(),
							"cont_add", Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_contEdit", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_edit",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_contDel",
					SysUtil.checkPermissionIsEnable(req.getSession(),
							"cont_del", Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_contReload", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_reload",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_contMove", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_move",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_contLink", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_link",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_contCopy", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_copy",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_contLock", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_lock",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_contTop",
					SysUtil.checkPermissionIsEnable(req.getSession(),
							"cont_top", Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_contRecommend", SysUtil
					.checkPermissionIsEnable(req.getSession(),
							"cont_recommend", Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_contExport", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_export",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_contImport", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_import",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_contPublish", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_publish",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_contSearch", SysUtil
					.checkPermissionIsEnable(req.getSession(), "cont_search",
							Long.valueOf(id),
							PermissionModelEntity.MODEL_TYPE_SITE));

		}
		return "manage/content/index";
	}

	@RequestMapping("Manage/Content/list.do")
	public void list(String nodeId, HttpServletResponse resp, String order,
			Integer page, Integer rows, String sort, String queryString,
			HttpServletRequest req) throws IOException {
		sort = StringUtils.isEmpty(sort) ? "id" : sort;
		order = StringUtils.isEmpty(order) ? "desc" : order;
		page = page == null || page <= 0 ? page = 1 : page;
		rows = rows == null || rows <= 0 ? 10 : rows;
		contentService = (IContentService) ServiceProxyFactory
				.getServiceProxy(ContentServiceImpl.class);
		String ss[] = nodeId.split("_");
		String query = "";
		List<ContentAttrEntity> attrList = null;
		if (ss.length == 2) {
			query = " where subSiteId=" + ss[1];
		} else {
			query = " where nodeIdPath like '%," + nodeId + ",%'";
			if (StringUtils.isNumeric(nodeId) && page == 1) {
				IContentAttrService attrServ = (IContentAttrService) getService(ContentAttrServiceImpl.class);
				attrList = attrServ.getAttrListByLinkToNodeId(Long
						.valueOf(nodeId));
			}
		}
		if (queryString != null && !queryString.trim().equals("")) {
			query += " and title like '%" + queryString.trim() + "%'";
		}
		query += " and deleted=false";
		List<ContentEntity> etList = contentService.getList("from "
				+ contentService.getTableName() + query, null, sort + " "  
				+ order, rows, rows * (page - 1));
		Long rowCount = contentService.getRowCount(query, null);
		if (attrList != null) {
			for (ContentAttrEntity attr : attrList) {
				ContentEntity c = contentService.getEntityById(attr
						.getContentId());//这里应该做个判断，并作处理
				if(c==null) 
					continue;
				c.setTitle("<font color='red'>[链]</font>" + c.getTitle());
				etList.add(c);
			}
		}
		try {
			JSONArray jsonArray = null;// JSONArray.fromObject( etList.toArray()
										// );
			jsonArray = JSONArray.fromObject(etList.toArray());
			PrintWriter out = resp.getWriter();
			out.print("{\"total\":" + rowCount.toString() + ",\"rows\":"
					+ jsonArray + "}");
			out.flush();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping("Manage/Content/props.do")
	public String props(Long id, Model model, HttpServletRequest req) {
		if (id != null && id != -1) {
			contentService = (IContentService) ServiceProxyFactory
					.getServiceProxy(ContentServiceImpl.class);
			ContentEntity content = contentService.getEntityById(id);
			if (content != null) {
				model.addAttribute("entity", content);
				model.addAttribute("propSaveEnable", SysUtil
						.checkPermissionIsEnable(req.getSession(),
								"cont_prop_save", content.getNodeId(),
								PermissionModelEntity.MODEL_TYPE_NODE));
			}
			// 寻找表单并压入前台
			INodeFormService nodeFormService = (INodeFormService) ServiceProxyFactory
					.getServiceProxy(NodeFormServiceImpl.class);
			NodeFormExtEntity nodeForm = nodeFormService.getNodeForm(
					NodeFormEntity.FORMTYPE_CONTENTFORM, content.getNodeId(),
					null);
			if(nodeForm==null){
				model.addAttribute(ERROR_MSG,"栏目没有对应的表单,请先设置.");
				return ERROR_PAGE;
			}
			model.addAttribute("nodeForm", nodeForm);
			model.addAttribute("fields", nodeForm.getNodeFormFieldList());
		}   
		return "manage/content/props";
	} 

	@RequestMapping("Manage/Content/saveProp.do") 
	public void saveProps(Long id, String field, String value,
			HttpServletResponse resp) throws NoSuchMethodException,
			SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {
		if (id != null && id != -1) {
			contentService = (IContentService) ServiceProxyFactory
					.getServiceProxy(ContentServiceImpl.class);
			ContentEntity cnt = contentService.getEntityById(id);
			if (cnt != null) {
				// 先确定参数类型
				Method tmpMethod = cnt.getClass().getMethod(
						"get" + field.substring(0, 1).toUpperCase()
								+ field.substring(1), new Class[] {});

				Method method = cnt.getClass().getMethod(
						"set" + field.substring(0, 1).toUpperCase()
								+ field.substring(1),
						new Class[] { tmpMethod.getReturnType() });
				Object val = getValue(value, tmpMethod.getReturnType()
						.getSimpleName());
				IbpdLogger.getLogger(this.getClass()).info("value=" + val);
				method.invoke(cnt, val);
				cnt.setLastUpdateDate(new Date());
				contentService.saveEntity(cnt);
			}
		}
	}

	@RequestMapping("Manage/Content/state.do")
	public void state(Long id, HttpServletResponse resp)
			throws NoSuchMethodException, SecurityException,
			IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {
		if (id != null && id != -1) {
			contentService = (IContentService) ServiceProxyFactory
					.getServiceProxy(ContentServiceImpl.class);
			ContentEntity cnt = contentService.getEntityById(id);
			if (cnt != null) {
				cnt.setState(cnt.getState() == 1 ? 0 : 1);
				cnt.setLastUpdateDate(new Date());
				contentService.saveEntity(cnt);
			}
		}
	}

	@RequestMapping("Manage/Content/publish.do")
	public void publish(String ids, HttpServletResponse resp)
			throws IOException {
		if (StringUtils.isBlank(ids)) {
			super.printMsg(resp, "-1", "-1", "参数不足");
			return;
		}
		String[] idarr = ids.split(",");
		for (String id : idarr) {
			if (StringUtils.isNumeric(id)) {
				this.makeStaticPage(MakeType.内容, Long.valueOf(id), null, null);
			}
		}
		super.printMsg(resp, "99", "99", "发布成功");
	}
	@RequestMapping("Manage/Content/toImport.do")
	public String toImport(String nodeId, HttpServletResponse resp,Model model){
		if (StringUtils.isBlank(nodeId)) {
			model.addAttribute(ERROR_MSG,MSG_PARAMERROR_MSG);
			return super.ERROR_PAGE;
		}
		model.addAttribute("nodeId",nodeId);
		if(nodeId.split("_").length==2){
			model.addAttribute("currentSiteId",nodeId.split("_")[1]);
			model.addAttribute("nodeId","-1");
		}else{
			model.addAttribute("siteId","");
			model.addAttribute("nodeId",nodeId);
		}
		return "manage/content/import";
	}
	@RequestMapping("Manage/Content/doImport.do")
	public void doImport(String siteId,String nodeId,HttpServletRequest req,HttpServletResponse resp,Model model) throws IOException{
		if(nodeId==null || siteId==null){
			super.printMsg(resp, "-1", "-1", "参数缺失");
			return;
		}
		NodeEntity node=null;
		String uploadPath=req.getRealPath("/uploadFiles/");
		INodeService nodeServ=(INodeService) getService(NodeServiceImpl.class);
		INodeAttrService nodeAttrServ=(INodeAttrService) getService(NodeAttrServiceImpl.class);
		if(nodeId!=null){
			node=nodeServ.getEntityById(Long.valueOf(nodeId));
		}else{
			node=new NodeEntity();
			node.setSubSiteId(Long.valueOf(siteId));
			node.setDepth(0);
			node.setParentId(-1L);
			node.setNodeIdPath(",");
			node.setId(-1L);
		}
		if(node!=null){
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置内存缓冲区，超过后写入临时文件
			factory.setSizeThreshold(10240000);
			// 设置临时文件存储位置
			
			String basePath = uploadPath;
			File fbasePath = new File(basePath);
			if(!fbasePath.exists())
				fbasePath.mkdirs();
				factory.setRepository(fbasePath);
				ServletFileUpload upload = new ServletFileUpload(factory);
				// 设置单个文件的最大上传值
				upload.setFileSizeMax(1024*1024*100);
				// 设置整个request的最大值
				upload.setSizeMax(1024*1024*100*20);
				upload.setHeaderEncoding("UTF-8");
				
				try {
					List<?> items = upload.parseRequest(req);
					FileItem item = null;
					String fileName = null;
						item = (FileItem) items.get(0);
						if(!item.getName().substring(item.getName().length()-3).toLowerCase().equals("zip")){
							super.printMsg(resp, "-2", "-2", "文件格式 错误 ");
							return;
						}
						String newFileName=item.getName()+"_"+RandomUtil.randomString(10)+".csv";
						fileName = basePath + File.separator + newFileName;
						if (!item.isFormField() && item.getName().length() > 0){
							item.write(new File(fileName));
						}
						File f=new File(fileName);
						String destPath=f.getParentFile().getAbsolutePath()+File.separator+f.getName()+"_unzip"+File.separator;
						UnZip.unZipFiles(f, destPath);
						File ff=new File(destPath);
						File[] fs=ff.listFiles();
						IContentService contServ=(IContentService) getService(ContentServiceImpl.class);
						for(File sf:fs){
							String txt=TxtUtil.readTxtFile(sf.getAbsolutePath(), "GB2312");
							txt=txt.replace("\r", "");
							String[] txts=txt.split("\n");
							if(txts.length>=3){
								String title=txts[0];
								String author=txts[1];
								String conts=getContents(txts);
								ContentEntity ce=new ContentEntity();
								ce.setTitle(title);
								ce.setAuthor(author);
								ce.setText(conts);
								ce.setNodeId(node.getId());
								ce.setNodeIdPath(node.getNodeIdPath());
								ce.setSubSiteId(node.getSubSiteId());
								ce.setCreateDate(new Date());
								ce.setDeleted(false);
								ce.setEnteringUser(SysUtil.getCurrentLoginedUserName(req
										.getSession()));
								ce.setLastUpdateDate(new Date());
								ce.setState(1);
								contServ.saveEntity(ce);
							}
						}
						super.printMsg(resp, "99", "99", "导入完成");
						return;
				} catch (FileUploadException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}				
		}
		super.printMsg(resp, "-1", "-1", "参数缺失");
	}
	private String getContents(String[] txts){
		if(txts.length<3){
			return "";
		}else{
			String s="";
			for(Integer i=3;i<txts.length;i++){
				s+=txts[i]+"\n";
			}
			return s;
		}
	}
	@RequestMapping("Manage/Content/toCopy.do")
	public String toCopy(String ids, HttpServletResponse resp,Model model){
		if (StringUtils.isBlank(ids)) {
			model.addAttribute(ERROR_MSG,MSG_PARAMERROR_MSG);
			return super.ERROR_PAGE;
		}
		IContentService contServ=(IContentService) getService(ContentServiceImpl.class);
		String hql="from "+contServ.getTableName()+" where ";
		String[] spids=ids.split(",");
		for(String id:spids){
			if(StringUtil.isNumeric(id)){
				hql+=" id="+id+" or ";
			}
		}
		hql+=" id=-1";
		List<ContentEntity> contList=contServ.getList(hql, null);
		model.addAttribute("copyContentList",contList);
		if(contList!=null && contList.size()>0)
			model.addAttribute("currentSiteId",contList.get(0).getSubSiteId());
		return "manage/content/copy";
	}
	@RequestMapping("Manage/Content/doCopy.do")
	public void doCopy(OrderMap map,HttpServletRequest req,HttpServletResponse resp) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		//逻辑：根据传值的KV键值对，取出要移动的栏目ID和移动目标栏目的ID，然后检索出移动栏目的所有子栏目以及下面的内容，更新自身和子栏目、内容的 nodeId,parentId,nodeIdPath，保存之,最后将目标栏目的leaf置为true即可
		if(map!=null || !map.getoMap().isEmpty()){
			IContentService contServ=(IContentService) getService(ContentServiceImpl.class);
			INodeService nodeServ=(INodeService) getService(NodeServiceImpl.class);
			IContentAttrService attrServ=(IContentAttrService) getService(ContentAttrServiceImpl.class);
			Set<String> sourceIdSet=map.getoMap().keySet();
			for(String sourceId:sourceIdSet){
				if(StringUtil.isNumeric(sourceId.trim())){
					ContentEntity sourceCont=contServ.getEntityById(Long.valueOf(sourceId));
					if(sourceCont!=null){
						ContentAttrEntity attr=attrServ.getContentAttr(sourceCont.getId());
						if(attr==null){
							attr=new ContentAttrEntity();
							attr.setContentId(sourceCont.getId());
						}
						String targetIds=map.getoMap().get(sourceId);
						if(!StringUtils.isBlank(targetIds)){
							String copyToNodeIds=targetIds.replace(",", ":");
							attr.setCopyTo(attr.getCopyTo()+":"+copyToNodeIds);
							String[] ids=targetIds.split(",");
							for(String nodeId:ids){
								NodeEntity tmpNode=nodeServ.getEntityById(Long.valueOf(nodeId));
								if(tmpNode!=null){
									ContentEntity targetCont=new ContentEntity();
									super.swap(sourceCont, targetCont);
									targetCont.setId(null);
									targetCont.setSubSiteId(tmpNode.getSubSiteId());
									targetCont.setNodeId(tmpNode.getId());
									targetCont.setNodeIdPath(tmpNode.getNodeIdPath());
									contServ.saveEntity(targetCont);
									attr.setCopyToContentIds(attr.getCopyToContentIds()+targetCont.getId()+":");
								}
							}
							attrServ.saveEntity(attr);
						}
					}
				}
			}
			printDefaultSuccessMsg(resp);
		}else{
			printParamErrorMsg(resp);
		}
	}
	@RequestMapping("Manage/Content/doMove.do")
	public void doMove(OrderMap map,HttpServletRequest req,HttpServletResponse resp) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		//逻辑：根据传值的KV键值对，取出要移动的栏目ID和移动目标栏目的ID，然后检索出移动栏目的所有子栏目以及下面的内容，更新自身和子栏目、内容的 nodeId,parentId,nodeIdPath，保存之,最后将目标栏目的leaf置为true即可
		if(map!=null || !map.getoMap().isEmpty()){
			IContentService contServ=(IContentService) getService(ContentServiceImpl.class);
			INodeService nodeServ=(INodeService) getService(NodeServiceImpl.class);
			Set<String> sourceIdSet=map.getoMap().keySet();
			for(String sourceId:sourceIdSet){
				if(StringUtil.isNumeric(sourceId.trim())){
					ContentEntity sourceCont=contServ.getEntityById(Long.valueOf(sourceId));
					if(sourceCont!=null){
						String targetIds=map.getoMap().get(sourceId);
						if(!StringUtils.isBlank(targetIds)){
							String[] ids=targetIds.split(",");
							for(String nodeId:ids){
								NodeEntity tmpNode=nodeServ.getEntityById(Long.valueOf(nodeId));
								if(tmpNode!=null){
									sourceCont.setNodeId(tmpNode.getId());
									sourceCont.setNodeIdPath(tmpNode.getNodeIdPath());
									contServ.saveEntity(sourceCont);
								}
								
							}
						}
					}
				}
			}
			printDefaultSuccessMsg(resp);
		}else{
			printParamErrorMsg(resp);
		}
	}
	@RequestMapping("Manage/Content/doLink.do")
	public void dolink(OrderMap map,HttpServletRequest req,HttpServletResponse resp) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		//逻辑：根据传值的KV键值对，取出要移动的栏目ID和移动目标栏目的ID，然后检索出移动栏目的所有子栏目以及下面的内容，更新自身和子栏目、内容的 nodeId,parentId,nodeIdPath，保存之,最后将目标栏目的leaf置为true即可
		if(map!=null || !map.getoMap().isEmpty()){
			IContentService contServ=(IContentService) getService(ContentServiceImpl.class);
			IContentAttrService attrServ=(IContentAttrService) getService(ContentAttrServiceImpl.class);
			Set<String> sourceIdSet=map.getoMap().keySet();
			for(String sourceId:sourceIdSet){
				if(StringUtil.isNumeric(sourceId.trim())){
					ContentEntity sourceCont=contServ.getEntityById(Long.valueOf(sourceId));
					ContentAttrEntity attr=attrServ.getContentAttr(sourceCont.getId());
					if(attr==null){
						attr=new ContentAttrEntity();
						attr.setContentId(sourceCont.getId());
					}
					if(sourceCont!=null){
						String targetIds=map.getoMap().get(sourceId);
						if(!StringUtils.isBlank(targetIds)){
							targetIds=targetIds.replace(",", ":");
							attr.setLinkTo(attr.getLinkTo()+":"+targetIds+":");
							attrServ.saveEntity(attr);
						}
					}
				}
			}
			printDefaultSuccessMsg(resp);
		}else{
			printParamErrorMsg(resp);
		}
	}
	@RequestMapping("Manage/Content/toMove.do")
	public String toMove(String ids, HttpServletResponse resp,Model model){
		if (StringUtils.isBlank(ids)) {
			model.addAttribute(ERROR_MSG,MSG_PARAMERROR_MSG);
			return super.ERROR_PAGE;
		}
		IContentService contServ=(IContentService) getService(ContentServiceImpl.class);
		String hql="from "+contServ.getTableName()+" where ";
		String[] spids=ids.split(",");
		for(String id:spids){
			if(StringUtil.isNumeric(id)){
				hql+=" id="+id+" or ";
			}
		}
		hql+=" id=-1";
		List<ContentEntity> contList=contServ.getList(hql, null);
		model.addAttribute("moveContentList",contList);
		if(contList!=null && contList.size()>0)
			model.addAttribute("currentSiteId",contList.get(0).getSubSiteId());
		return "manage/content/move";
	}
	@RequestMapping("Manage/Content/toLink.do")
	public String toLink(String ids, HttpServletResponse resp,Model model){
		if (StringUtils.isBlank(ids)) {
			model.addAttribute(ERROR_MSG,MSG_PARAMERROR_MSG);
			return super.ERROR_PAGE;
		}
		IContentService contServ=(IContentService) getService(ContentServiceImpl.class);
		String hql="from "+contServ.getTableName()+" where ";
		String[] spids=ids.split(",");
		for(String id:spids){
			if(StringUtil.isNumeric(id)){
				hql+=" id="+id+" or ";
			}
		}
		hql+=" id=-1";
		List<ContentEntity> contList=contServ.getList(hql, null);
		model.addAttribute("linkContentList",contList);
		if(contList!=null && contList.size()>0)
			model.addAttribute("currentSiteId",contList.get(0).getSubSiteId());
		return "manage/content/link";
	}
	@RequestMapping("Manage/Content/doExport.do")
	public void doExport(String ids, HttpServletResponse resp,HttpServletRequest req) throws Exception{
		String uploadFilePath="/uploadFiles/";
		if (StringUtils.isBlank(ids)) {
			printParamErrorMsg(resp);
			return;
		}
		IContentService contServ=(IContentService) getService(ContentServiceImpl.class);
		String hql="from "+contServ.getTableName()+" where ";
		String[] spids=ids.split(",");
		for(String id:spids){
			if(StringUtil.isNumeric(id)){
				hql+=" id="+id+" or ";
			}
		}
		hql+=" id=-1";
		List<ContentEntity> contList=contServ.getList(hql, null);
		//简单实现存入文件，然后压缩成zip包，最后 把下载地址推送到前台让下载
		String flName="contentExport_"+DateUtil.formatDate(new Date(), "yyyyMMddhhmmss")+"_{id}.txt";
		List<File> pathList=new ArrayList<File>();
		String uploadPath=req.getRealPath(uploadFilePath);
		for(ContentEntity c:contList){
			StringBuffer sb=new StringBuffer();
			sb.append(c.getTitle()+"\r\n");
			sb.append(c.getAuthor()+"\r\n");
			sb.append(c.getText()+"\r\n");
			String path=uploadPath+File.separator+flName.replace("{id}", c.getId().toString());
			File f=new File(path);
			pathList.add(f);
			TxtUtil.writeTxtFile(sb.toString(), f,"GB2312");
		}
		String newZipFileName=RandomUtil.randomString(10)+".zip";
		String zipFilePath=uploadPath+File.separator+newZipFileName;
		Zip.zipFiles(pathList,new File(zipFilePath));
		super.printMsg(resp, "99", "99", req.getContextPath()+uploadFilePath+newZipFileName);
	}
	@RequestMapping("Manage/Content/doState.do")
	public void state(String ids, HttpServletResponse resp,HttpServletRequest req) throws Exception{
		if (StringUtils.isBlank(ids)) {
			printParamErrorMsg(resp);
			return;
		}
		IContentService contServ=(IContentService) getService(ContentServiceImpl.class);
		String hql="from "+contServ.getTableName()+" where ";
		String[] spids=ids.split(",");
		for(String id:spids){
			if(StringUtil.isNumeric(id)){
				hql+=" id="+id+" or ";
			}
		}
		hql+=" id=-1";
		List<ContentEntity> contList=contServ.getList(hql, null);
		if(contList!=null && contList.size()>0){
			for(ContentEntity cont:contList){
				cont.setState(cont.getState()==ContentEntity.STATE_OPEN?ContentEntity.STATE_CLOSE:ContentEntity.STATE_OPEN);
				contServ.saveEntity(cont);
			}
		}
		super.printMsg(resp, "99", "99", "更新内容状态完成");
	}
	@RequestMapping("Manage/Content/doTop.do")
	public void top(String ids, HttpServletResponse resp,HttpServletRequest req) throws Exception{
		if (StringUtils.isBlank(ids)) {
			printParamErrorMsg(resp);
			return;
		}
		IContentService contServ=(IContentService) getService(ContentServiceImpl.class);
		String hql="from "+contServ.getTableName()+" where ";
		String[] spids=ids.split(",");
		for(String id:spids){
			if(StringUtil.isNumeric(id)){
				hql+=" id="+id+" or ";
			}
		}
		hql+=" id=-1";
		List<ContentEntity> contList=contServ.getList(hql, null);
		if(contList!=null && contList.size()>0){
			for(ContentEntity cont:contList){
				cont.setIsTop(!cont.getIsTop());
				contServ.saveEntity(cont);
			}
		}
		super.printMsg(resp, "99", "99", "更新内容置顶完成");
	}
	@RequestMapping("Manage/Content/doRecommend.do")
	public void recommend(String ids, HttpServletResponse resp,HttpServletRequest req) throws Exception{
		if (StringUtils.isBlank(ids)) {
			printParamErrorMsg(resp);
			return;
		}
		IContentService contServ=(IContentService) getService(ContentServiceImpl.class);
		String hql="from "+contServ.getTableName()+" where ";
		String[] spids=ids.split(",");
		for(String id:spids){
			if(StringUtil.isNumeric(id)){
				hql+=" id="+id+" or ";
			}
		}
		hql+=" id=-1";
		List<ContentEntity> contList=contServ.getList(hql, null);
		if(contList!=null && contList.size()>0){
			for(ContentEntity cont:contList){
				cont.setIsRecommend(!cont.getIsRecommend());
				contServ.saveEntity(cont);
			}
		}
		super.printMsg(resp, "99", "99", "更新内容推荐完成");
	}

	@RequestMapping("Manage/Content/toAdd.do")
	public String toAdd(String nodeId, Model model) {
		model.addAttribute(PAGE_TITLE, "添加文章");
		if (nodeId == null) {
			return this.ERROR_PAGE;
		}
		String[] ss = nodeId.split("_");
		if (ss.length == 2) {
			model.addAttribute(ERROR_MSG, "请选择栏目");
			return this.ERROR_PAGE;
		}
		if (!StringUtil.isNumeric(nodeId)) {
			model.addAttribute(ERROR_MSG, "参数不正确");
			return this.ERROR_PAGE;
		}
		model.addAttribute("nodeId", nodeId);
		model.addAttribute("type", "add");
		// 寻找表单并压入前台
		INodeFormService nodeFormService = (INodeFormService) ServiceProxyFactory
				.getServiceProxy(NodeFormServiceImpl.class);
		NodeFormExtEntity nodeForm = nodeFormService.getNodeForm(
				NodeFormEntity.FORMTYPE_CONTENTFORM, Long.parseLong(nodeId),
				null);
		if(nodeForm==null){
			model.addAttribute(ERROR_MSG,"栏目没有对应的表单,请先设置.");
			return ERROR_PAGE;
		}
		model.addAttribute("nodeForm", nodeForm);
		model.addAttribute("fields", nodeForm.getNodeFormFieldList());
		return "manage/content/add";
	}

	@RequestMapping("Manage/Content/toEdit.do")
	public String toEdit(Long contentId, Model model) {
		model.addAttribute(PAGE_TITLE, "编辑文章");
		model.addAttribute("type", "edit");
		if (contentId == null) {
			return this.ERROR_PAGE;
		}
		contentService = (IContentService) ServiceProxyFactory
				.getServiceProxy(ContentServiceImpl.class);
		ContentEntity ne = contentService.getEntityById(contentId);
		if (ne == null) {
			return this.ERROR_PAGE;
		}
		IContentAttrService caService = (IContentAttrService) ServiceProxyFactory
				.getServiceProxy(ContentAttrServiceImpl.class);
		model.addAttribute("entity", ne);
		model.addAttribute("type", "edit");
		model.addAttribute("text", ne.getText().replace("\r", "").replace("\n",
				""));
		model.addAttribute("titleFormatParameters", caService.getTitleFormat(ne
				.getId()));
		model.addAttribute("copyTo", caService.getCopyTo(ne.getId()));
		model.addAttribute("linkTo", caService.getLinkTo(ne.getId()));
		// 寻找表单并压入前台
		INodeFormService nodeFormService = (INodeFormService) ServiceProxyFactory
				.getServiceProxy(NodeFormServiceImpl.class);
		NodeFormExtEntity nodeForm = nodeFormService.getNodeForm(
				NodeFormEntity.FORMTYPE_CONTENTFORM, ne.getNodeId(), null);
		model.addAttribute("nodeForm", nodeForm);
		model.addAttribute("fields", nodeForm.getNodeFormFieldList());

		return "manage/content/add";
	}

	@RequestMapping("Manage/Content/doEdit.do")
	public void doEdit(@ModelAttribute() ContentEntity entity,
			HttpServletResponse resp, String titleFormatParams, String copyTo,
			String linkTo) throws IOException, NoSuchMethodException,
			SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {
		if (entity != null && entity.getId() != null && entity.getId() != -1L) {
			IbpdLogger.getLogger(this.getClass()).info(
					"titleFormatParams=" + titleFormatParams + " copyTo="
							+ copyTo + " linkTo=" + linkTo);
			// titleFormatParams=color:#FF0000;strong:;em:;u:;size: copyTo=
			// linkTo=
			contentService = (IContentService) ServiceProxyFactory
					.getServiceProxy(ContentServiceImpl.class);
			ContentEntity ne = contentService.getEntityById(entity.getId());
			if (ne == null) {
				String res = getJsonResult("-2", "" + entity.getId(), "没有找到该内容");
				resp.getWriter().write(res);
				resp.getWriter().flush();
			} else {
				String nodeIdPath = ne.getNodeIdPath();
				Integer state = ne.getState();
				Boolean deleted = ne.getDeleted();
				Long siteId = ne.getSubSiteId();
				swap(ne, entity);
				ne.setNodeIdPath(nodeIdPath);
				ne.setState(state);
				ne.setDeleted(deleted);
				ne.setSubSiteId(siteId);
				ne.setLastUpdateDate(new Date());
				contentService.saveEntity(ne);
				IContentAttrService caService = (IContentAttrService) ServiceProxyFactory
						.getServiceProxy(ContentAttrServiceImpl.class);
				ContentAttrEntity caEntity = caService.getContentAttr(ne
						.getId());
				caEntity = caEntity == null ? new ContentAttrEntity()
						: caEntity;
				Map<String, String> pams = getFormatMap(titleFormatParams);
				caEntity.setColor(pams.get("color"));
				caEntity.setContentId(entity.getId());
				caEntity.setCopyTo(":" + copyTo.replace(",", ":") + ":");
				caEntity.setEm(getBoolean(pams.get("em")));
				caEntity.setLinkTo(":" + linkTo.replace(",", ":") + ":");
				caEntity.setSize(pams.get("size"));
				caEntity.setStrong(getBoolean(pams.get("strong")));
				caEntity.setU(getBoolean(pams.get("u")));
				caService.saveEntity(caEntity);
				// copyTo fun
				// String[] nodeIds=copyTo.split(",");
				// if(copyTo!=null && !copyTo.trim().equals("")){
				// INodeService nodeSer=(INodeService)
				// ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
				// for(String nodeId:nodeIds){
				// NodeEntity
				// node=nodeSer.getEntityById(Long.parseLong(nodeId));
				// ContentEntity ce=new ContentEntity();
				// swap(ce,entity);
				// ce.setId(null);
				// ce.setNodeId(node.getId());
				// ce.setNodeIdPath(node.getNodeIdPath());
				// contentService.saveEntity(ce);
				// }
				// }
				String res = getJsonResult("99", "" + entity.getId(), "保存成功");
				resp.getWriter().write(res);
				resp.getWriter().flush();
			}
		} else {
			String res = getJsonResult("-1", "", "ID为空");
			resp.getWriter().write(res);
			resp.getWriter().flush();
		}

	}

	private IBaseEntity swap(IBaseEntity dbEntity, IBaseEntity obEntity)
			throws NoSuchMethodException, SecurityException,
			IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {
		Method[] methods = obEntity.getClass().getMethods();
		for (Method getMethod : methods) {
			String getMethodName = getMethod.getName();
			if (getMethodName.substring(0, 3).equals("get")
					&& !getMethodName.equals("getClass")) {
				String setMethodName = "set" + getMethodName.substring(3);
				Method setMethod = dbEntity.getClass().getMethod(setMethodName,
						getMethod.getReturnType());
				if (setMethod != null) {

					setMethod
							.invoke(dbEntity, getMethod.invoke(obEntity, null));
				}
			}
		}
		return dbEntity;
	}

	private Map<String, String> getFormatMap(String formatString) {
		Map<String, String> rtn = new HashMap<String, String>();
		if (formatString != null || !formatString.trim().equals("")) {
			String[] s = formatString.split(";");
			for (String ss : s) {
				String[] sss = ss.split(":");
				if (sss.length == 2) {
					rtn.put(sss[0], sss[1]);
				}
			}
		}
		return rtn;
	}

	@RequestMapping("Manage/Content/doAdd.do")
	public void doAdd(@ModelAttribute() ContentEntity entity,
			HttpServletRequest req, HttpServletResponse resp,
			String titleFormatParams, String copyTo, String linkTo)
			throws IOException, NoSuchMethodException, SecurityException,
			IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {
		IbpdLogger.getLogger(this.getClass()).info(
				"titleFormatParams=" + titleFormatParams + " copyTo=" + copyTo
						+ " linkTo=" + linkTo);
		// titleFormatParams=color:#FF0000;strong:;em:;u:;size: copyTo= linkTo=
		if (entity.getNodeId() == null) {
			String res = getJsonResult("-1", "-1", "没有设置 栏目信息,请联系管理员.");
			resp.getWriter().write(res);
			resp.getWriter().flush();
			return;
		}
		// System.out.println("entity.text="+entity.getText());
		if (entity.getTitle().trim().equals("")) {
			String res = getJsonResult("-1", "-1", "没有设置标题.");
			resp.getWriter().write(res);
			resp.getWriter().flush();
			return;
		}
		INodeService nodeService = (INodeService) ServiceProxyFactory
				.getServiceProxy(NodeServiceImpl.class);
		NodeEntity node = nodeService.getEntityById(entity.getNodeId());
		contentService = (IContentService) ServiceProxyFactory
				.getServiceProxy(ContentServiceImpl.class);
		entity.setNodeIdPath(node.getNodeIdPath());
		entity.setCreateDate(new Date());
		entity.setDeleted(false);
		entity.setEnteringUser(SysUtil.getCurrentLoginedUserName(req
				.getSession()));
		entity.setLastUpdateDate(new Date());
		entity.setState(1);
		entity.setSubSiteId(node.getSubSiteId());
		contentService.saveEntity(entity);
		// 保存内容属性信息
		IContentAttrService caService = (IContentAttrService) ServiceProxyFactory
				.getServiceProxy(ContentAttrServiceImpl.class);
		ContentAttrEntity caEntity = new ContentAttrEntity();
		Map<String, String> pams = getFormatMap(titleFormatParams);
		caEntity.setColor(pams.get("color"));
		caEntity.setContentId(entity.getId());
		caEntity.setCopyTo(":" + copyTo.replace(",", ":") + ":");
		caEntity.setEm(getBoolean(pams.get("em")));
		caEntity.setLinkTo(":" + linkTo.replace(",", ":") + ":");
		caEntity.setSize(pams.get("size"));
		caEntity.setStrong(getBoolean(pams.get("strong")));
		caEntity.setU(getBoolean(pams.get("u")));
		// 保存【复制到】的信息
		String[] nodeIds = copyTo.split(",");
		if (copyTo != null && !copyTo.trim().equals("")) {
			INodeService nodeSer = (INodeService) ServiceProxyFactory
					.getServiceProxy(NodeServiceImpl.class);
			for (String nodeId : nodeIds) {
				NodeEntity tmpNode = nodeSer.getEntityById(Long
						.parseLong(nodeId));
				ContentEntity ce = new ContentEntity();
				swap(ce, entity);
				ce.setId(null);
				ce.setNodeId(tmpNode.getId());
				ce.setNodeIdPath(tmpNode.getNodeIdPath());
				ce.setSubSiteId(tmpNode.getSubSiteId());
				contentService.saveEntity(ce);
				caEntity.setCopyToContentIds(caEntity.getCopyToContentIds()
						+ "," + ce.getId() + ",");
			}
		}
		// 将内容attr信息保存起来，包括已经复制过去的信息
		caService.saveEntity(caEntity);

		String res = getJsonResult("99", "" + entity.getId(), "保存成功");
		resp.getWriter().write(res);
		resp.getWriter().flush();

	}

	private Boolean getBoolean(String v) {
		// titleFormatParams=color:#FF0000;strong:1;em:1;u:1;size:22px
		// copyTo=12,13 linkTo=32,150
		if (v == null)
			return false;
		if (v.trim().toLowerCase().equals("1")) {
			return true;
		} else {
			return false;
		}
	}

	@RequestMapping("Manage/Content/saveText.do")
	public void saveText(String id, String content, HttpServletResponse resp)
			throws IOException {
		if (id == null || id.trim().equals("")) {
			String res = getJsonResult("-1", "-1", "没有内容ID，内容基本信息没有保存成功.");
			resp.getWriter().write(res);
			resp.getWriter().flush();
			return;
		}
		contentService = (IContentService) ServiceProxyFactory
				.getServiceProxy(ContentServiceImpl.class);
		ContentEntity c = contentService.getEntityById(Long.parseLong(id));
		if (c == null) {
			String res = getJsonResult("-2", "-1", "没有找到相应内容.");
			resp.getWriter().write(res);
			resp.getWriter().flush();
		} else {
			IContentAttrService ca = (IContentAttrService) ServiceProxyFactory
					.getServiceProxy(ContentAttrServiceImpl.class);
			String cids = ca.getCopyToContentIds(c.getId());

			c.setText(content);
			// 开始设置复制到的内容text信息
			if (cids != null && !cids.trim().equals("")) {
				for (String cid : cids.split(",")) {
					if (cid.equals(""))
						continue;
					ContentEntity tc = contentService.getEntityById(Long
							.parseLong(cid));
					if (tc != null) {
						tc.setText(content);
						contentService.saveEntity(tc);
					}
				}
			}

			contentService.saveEntity(c);
			// String res=getJsonResult("99",""+c.getId(),"保存成功.");
			// resp.getWriter().write(res);
			super.printJsonData(resp, getJsonResult("99", "" + c.getId(),
					"保存成功."));
			// resp.getWriter().flush();
		}
	}

	@RequestMapping("Manage/Content/formatTitle.do")
	public String formatTitle(HttpServletRequest req, HttpServletResponse resp,
			Model model) throws UnsupportedEncodingException {
		if (req.getParameter("txt") == null)
			return ERROR_PAGE;
		String txt = new String(req.getParameter("txt").getBytes("ISO-8859-1"),
				"utf-8");
		IbpdLogger.getLogger(this.getClass()).info("sss=" + txt);
		model.addAttribute("txt", txt);
		return "manage/content/formatTitle";
	}

	// @RequestMapping("Manage/Content/saveTitleFormat.do")
	// public void formatTitle(String strong,String em,String u,String
	// curColor){
	// System.out.println("color:"+curColor+" strong:"+strong+" em:"+em+" u:"+u);
	// }
	/**
	 * 本来是计划用来更新字段值来着，结果也就用来 做更新“是否已经删除”字段的值了
	 * 
	 * @param ids
	 * @param resp
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	@RequestMapping("Manage/Content/recv.do")
	public void props(String ids, HttpServletResponse resp)
			throws NoSuchMethodException, SecurityException,
			IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {
		if (ids != null) {
			String whereString = " where ";
			List<HqlParameter> pList = new ArrayList<HqlParameter>();
			if (ids.substring(ids.trim().length() - 1).equals(",")) {
				String[] id = ids.split(",");
				for (Integer i = 0; i < id.length; i++) {
					pList.add(new HqlParameter("id" + i, Long.parseLong(id[i]),
							DataType_Enum.Long));
					whereString += "id=:id" + i + " or ";
				}
			}
			whereString = whereString.substring(0, whereString.length() - 4);
			contentService = (IContentService) ServiceProxyFactory
					.getServiceProxy(ContentServiceImpl.class);
			List<ContentEntity> contentList = contentService.getList("from "
					+ contentService.getTableName() + whereString, pList);
			if (contentList != null) {
				List<HqlParameter> tList = new ArrayList<HqlParameter>();
				ContentEntity simpNode = null;
				for (Integer i = 0; i < contentList.size(); i++) {
					ContentEntity ne = contentList.get(i);
					ne.setDeleted(true);
					simpNode = simpNode == null ? ne : simpNode;
					ne.setLastUpdateDate(new Date());
					contentService.saveEntity(ne);
				}
				IbpdLogger.getLogger(this.getClass()).info("||||||||");
				// tList.add(new
				// HqlParameter("id",simpNode.getParentId(),DataType_Enum.Long));
				// List<ContentEntity>
				// parentList=contentService.getList("from "+contentService.getTableName()+" where id=:id",tList);
				// for(ContentEntity pn:parentList){
				// pn.setChildCount(pn.getChildCount()>=contentList.size()?pn.getChildCount()-contentList.size():0);
				// if(pn.getChildCount()==0){
				// pn.setLeaf(false);
				// }
				// contentService.saveEntity(pn);
				// }
			}
		}

	}
}
